const express=require('express');
const cookieParser=require('cookie-parser');
const cookiesSession=require('cookie-session');
const userService=require('../services/userService');

var router=express.Router();



router.use('/loginPage.html',async function (req,res,next) {
    var user=req.cookies['user'];
    // console.log('views1',user);
    if(user==undefined||user=={}){
        console.log('cookies is null');
        next();
    }else if(user.role=='admin'){
        console.log('role admin is not login!');
        next();
    }else{
        //自动登录的过程
        var data=await userService.loginCookie(user);
        console.log('role user auto login!');
        if(data.success){
            req.session['user']=data.user;
            //这个过程是客户端发出的信息
            res.redirect('/views/pages/user1.html');//重新转发到另外一个页面上
        }else{
            next();
        }
    }
})

//views路由上做登陆使用控制
//要进入pages下面的页面，必须是登录状态，否则全部进入/views/loginPage.html
router.use('/pages',function(req,res,next){
    var user=req.session.user;
    if(user==null||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else{
        next();
    }
})

router.use('/admin',(req,res,next)=>{
    var user=req.session.user;
    if(user==[]||user=={}||user==undefined||user==''){
        res.redirect('/views/loginPage.html');
    }else if(user.role=='user'){
        res.redirect('/views/loginPage.html');
    }else{
        next();
    }
})
exports.router=router;